<script setup>
import CentralizedLayout from "../layout/CentralizedLayout.vue";
import CommonLayout from "../layout/CommonLayout.vue";

import {ref} from 'vue'
import api from "../utils/axios.js";
import {ElNotification} from "element-plus";
import ReactiveElOption from "../components/ReactiveElOption.vue";

let tableData = ref([])
const genderData = [
  {
    id: 1,
    name: "男"
  },
  {
    id: 2,
    name: "女"
  }
]
let departmentData = ref([])
let majorData = ref([])
let classeData = ref([])
const editIndex = ref(-1)
const tableHeaders = [
  {
    name: "ID",
    key: "id",
    generated: true,
    type: "text"
  },
  {
    name: "姓名",
    key: "name",
    generated: false,
    type: "text"
  },
  {
    name: "性别",
    key: "gender",
    generated: false,
    type: "select",
    selectSource: genderData,
    selectKey: "name"
  },
  {
    name: "生日",
    key: "birthday",
    generated: false,
    type: "date"
  },
  {
    name: "学号",
    key: "schoolId",
    generated: true,
    type: "text"
  },
  {
    name: "学院",
    key: "department",
    generated: false,
    type: "select",
    selectSource: [],
    selectKey: "name"
  },
  {
    name: "专业",
    key: "major",
    generated: false,
    type: "select",
    selectSource: [],
    selectKey: "name"
  },
  {
    name: "班级",
    key: "classe",
    generated: false,
    type: "select",
    selectSource: [],
    selectKey: "name"
  },
  {
    name: "入学日期",
    key: "batch",
    generated: false,
    type: "year"
  },
]

function initialData() {
  api({
    method: "get",
    url: "api/affair/department"
  }).then(response => {
    departmentData.value = response.data
    tableHeaders.at(5)["selectSource"] = response.data
  }).catch(error => errorNotification(error))

  api({
    method: "get",
    url: "api/affair/major"
  }).then(response => {
    majorData.value = response.data
    tableHeaders.at(6)["selectSource"] = response.data
  }).catch(error => errorNotification(error))

  api({
    method: "get",
    url: "api/affair/classe"
  }).then(response => {
    classeData.value = response.data
    tableHeaders.at(7)["selectSource"] = response.data
  }).catch(error => errorNotification(error))

}
initialData()

function retrieveData() {
  api({
    method: "get",
    url: "api/personnel/student"
  }).then(response => {
    tableData.value = response.data
    readable(tableData.value, "gender", genderData, "id", "name")
    readable(tableData.value, "department", departmentData.value, "id", "name")
    readable(tableData.value, "major", majorData.value, "id", "name")
    readable(tableData.value, "classe", classeData.value, "id", "name")
  }).catch(error => errorNotification(error))
}

onMounted(retrieveData)

const handleEdit = (row) => {
  editIndex.value = tableData.value.indexOf(row)
}

const handleSave = (row) => {
  editIndex.value = -1
  let newRow = {}
  Object.assign(newRow, row)
  transferable(newRow, "gender", genderData, "id", "name")
  transferable(newRow, "department", departmentData.value, "id", "name")
  transferable(newRow, "major", majorData.value, "id", "name")
  transferable(newRow, "classe", classeData.value, "id", "name")
  console.log(newRow)
}

const handleDelete = (row) => {
  tableData.value.splice(tableData.value.indexOf(row), 1)
}

function createRow() {
  let keys = []
  tableHeaders.forEach((header) => {
    keys.push(header["key"])
  })

  let newRow = {}
  keys.forEach((key) => {
    newRow[key] = ""
  })
  tableData.value.push(newRow)
}

function readable(sourceArray, sourceKey, saltArray, saltIndex, saltKey) {
  sourceArray.forEach((sourceItem) => {
    saltArray.forEach((saltItem) => {
      if (sourceItem[sourceKey].toString() === saltItem[saltIndex].toString()) {
        sourceItem[sourceKey] = saltItem[saltKey]
      }
    })
  })
}

function transferable(sourceItem, sourceKey, saltArray, saltIndex, saltKey) {
  saltArray.forEach((saltItem) => {
    if (sourceItem[sourceKey] === saltItem[saltKey]) {
      sourceItem[sourceKey] = saltItem[saltIndex]
    }
  })
}

function errorNotification(error) {
  console.log(error)
  ElNotification({
    title: "系统错误",
    type: 'error',
    message: error.response.data.message
  })
}

</script>

<template>
  <CommonLayout>
    <CentralizedLayout>
      <el-card class="w-full">
        <template #header>
          <el-button type="primary" @click="createRow">新增</el-button>
        </template>
        <template #default>
          <el-table :data="tableData" border>
            <template v-for="column in tableHeaders">
              <el-table-column v-if="column.generated" :prop="column.key" :label="column.name"></el-table-column>
              <el-table-column v-else-if="column.type === 'text'" :label="column.name">
                <template #default="scope">
                  <span v-show="scope.$index !== editIndex">{{ scope.row[column.key] }}</span>
                  <el-input
                      v-show="scope.$index === editIndex"
                      v-model="scope.row[column.key]"
                  />
                </template>
              </el-table-column>
              <el-table-column v-else-if="column.type === 'select'" :label="column.name">
                <template #default="scope">
                  <span v-show="scope.$index !== editIndex">{{ scope.row[column.key] }}</span>
                  <el-select v-if="scope.$index === editIndex" v-model="scope.row[column.key]">
                    <ReactiveElOption :option-source="column.selectSource" :option-key="column.selectKey"/>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column v-else-if="column.type === 'year'" :label="column.name">
                <template #default="scope">
                  <span v-show="scope.$index !== editIndex">{{ scope.row[column.key] }}</span>
                  <el-date-picker
                      v-if="scope.$index === editIndex"
                      v-model="scope.row[column.key]"
                      type="year"
                      value-format="YYYY"
                      placeholder="选择年份"
                  />
                </template>
              </el-table-column>
              <el-table-column v-else :prop="column.key" :label="column.name"></el-table-column>
            </template>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button link @click="handleEdit(row)">编辑</el-button>
                <el-button type="primary" link @click="handleSave(row)">保存</el-button>
                <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </el-card>
    </CentralizedLayout>
  </CommonLayout>
</template>